package com.zhengqiangblog.blog.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;

import com.zhengqiangblog.blog.dao.common.JdbcDaoSupport;
import com.zhengqiangblog.blog.model.Category;
import com.zhengqiangblog.core.RowMapper;

public class CategoryDao extends JdbcDaoSupport {

	private static final Logger logger = Logger.getLogger(CategoryDao.class);

	private CategoryRowMapper categoryRowMapper = new CategoryRowMapper();

	public CategoryDao() {
		logger.info("CategoryDao initializing...");
	}

	public int saveCategory(Category category) throws Exception {
		String sql = "insert into category (name) values (?)";
		return this.getJdbcTemplate().update(sql, category.getName());
	}

	public int deleteCategory(int categoryId) throws Exception {
		String sql = "delete from category where id = ?";
		return this.getJdbcTemplate().update(sql, categoryId);
	}

	public List<Category> getCategoryList() throws Exception {
		String sql = "select id, name from category";
		return this.getJdbcTemplate().query(sql, categoryRowMapper);
	}

	public Category getCategory(int categoryId) throws Exception {
		String sql = "select id, name from category where id = ?";
		return this.getJdbcTemplate().queryForObject(sql, categoryRowMapper, categoryId);
	}

	public int updateCategory(Category category) throws Exception {
		String sql = "update category set name = ? where id = ?";
		return this.getJdbcTemplate().update(sql, category.getName(), category.getId());
	}

	private class CategoryRowMapper implements RowMapper<Category> {
		@Override
		public Category mapRow(ResultSet rs, int rowNum) throws SQLException {
			Category category = new Category();
			category.setId(rs.getInt("id"));
			category.setName(rs.getString("name"));
			return category;
		}
	}

}
